<template>
  <div class="app-container">
    <!--搜索栏-->
    <div class="filter-container">
      <el-input v-model="listQuery.search" clearable placeholder="关键字" style="width: 200px;" size="mini" @keyup.enter.native="handleFilter" @clear="handleFilter" />
      <el-select v-model="listQuery.state" placeholder="请选择" size="mini" clearable>
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" size="mini" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" size="mini" @click="handleCreate">新增</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" size="mini" @click="multipleDel">删除</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" size="mini" @click="handleLink">动态跳转</el-button>
    </div>
    <!--表格框-->
    <el-table v-loading="listLoading" :data="list" style="width: 100%;margin-top: 20px" border :header-cell-class-name="handleHeaderCellClass" @sort-change="sortChange" @selection-change="selectionChange">
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column label="序号" type="index" width="80" align="center">
        <template slot-scope="{$index}">
          <span>{{ (listQuery.pageIndex - 1) * listQuery.pageSize + ($index + 1) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" sortable="custom" prop="roleName" width="250" align="center" />
      <el-table-column label="是否超管" prop="isSuper" width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.isSuper?'是':'否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" sortable="custom" prop="remark" min-width="300" align="center" />
      <el-table-column label="状态" prop="state" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag type="warning">
            {{ row.state }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" fixed="right">
        <template slot-scope="{row}">
          <el-button type="text" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="text" @click="del(row.roleId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageIndex" :limit.sync="listQuery.pageSize" @pagination="find" />
    <!--新增/编辑弹框-->
    <el-dialog :title="dialogTile[dialogStatus]" :visible.sync="dialogFormVisible" width="460px">
      <el-form ref="dataForm" :rules="rules" :model="model" label-position="right" label-width="80px" style="width: 400px;">
        <el-form-item label="角色" prop="roleName">
          <el-input v-model="model.roleName" placeholder="请输入角色名称内容" />
        </el-form-item>
        <el-form-item label="备注备注" prop="remark">
          <el-input v-model="model.remark" type="textarea" :rows="4" placeholder="请输入内容" resize="none" style="width:318px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!--    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">-->
    <!--      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">-->
    <!--        <el-table-column prop="key" label="Channel" />-->
    <!--        <el-table-column prop="pv" label="Pv" />-->
    <!--      </el-table>-->
    <!--      <span slot="footer" class="dialog-footer">-->
    <!--        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>-->
    <!--      </span>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import { find, create, update, del } from '@/api/role'
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'

// const calendarTypeOptions = [
//   { key: 'CN', display_name: 'China' },
//   { key: 'US', display_name: 'USA' },
//   { key: 'JP', display_name: 'Japan' },
//   { key: 'EU', display_name: 'Eurozone' }
// ]

// arr to obj, such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
//   acc[cur.key] = cur.display_name
//   return acc
// }, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  // filters: {
  //   statusFilter(status) {
  //     const statusMap = {
  //       published: 'success',
  //       draft: 'info',
  //       deleted: 'danger'
  //     }
  //     return statusMap[status]
  //   },
  //   typeFilter(type) {
  //     return calendarTypeKeyValue[type]
  //   }
  // },
  data() {
    return {
      tableKey: 0,
      list: null,
      // HEINFO: 2020/7/7 0:37 数据总条数
      total: 0,
      // HEINFO: 2020/7/4 12:56 遮罩
      listLoading: true,
      listQuery: {
        pageSize: 2,
        pageIndex: 1,
        search: '',
        state: '',
        sort: ''
      },
      // 存储多字段排序数据
      sortList: [],
      // 存储批量删除ID
      delIds: '',
      options: [{ value: 'valid', label: '有效' }, { value: 'del', label: '删除' }],
      //   importanceOptions: [1, 2, 3],
      //   calendarTypeOptions,
      //   sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      // statusOptions: ['published', 'draft', 'deleted'],
      //   showReviewer: false,
      // heinfo 表单模型数据
      model: {
        id: undefined,
        roleName: '',
        remark: ''
      },
      // heinfo 表单框是否显示
      dialogFormVisible: false,
      // heinfo 表单状态
      dialogStatus: '',
      // heinfo 表单状态标题
      dialogTile: {
        update: '编辑',
        create: '新增'
      },
      //   dialogPvVisible: false,
      //   pvData: [],
      // heinfo 表单验证规则
      rules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    //   downloadLoading: false
    }
  },
  watch: {
    // HEINFO: 2020/7/6 10:25 监听 search
    // 'listQuery.search'() {
    //   this.find()
    // }
  },
  created() {
    this.find()
  },
  methods: {
    // HEINFO: 2020/7/4 14:36 查询
    find() {
      this.listLoading = true
      find(this.listQuery).then((res) => {
        // console.log(res)
        this.list = res.data.list
        this.total = res.data.total
      }).then(() => {
        setTimeout(() => {
          this.listLoading = false
        }, 200)
      })
    },
    // HEINFO: 2020/7/4 14:36 过滤查询
    handleFilter() {
      this.find()
    },
    // HEINFO: 2020/7/4 14:34 新增前处理： 重置模板、显示表单弹框、清除验证
    handleCreate() {
      this.model = {
        id: undefined,
        roleName: '',
        remark: ''
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // HEINFO: 2020/7/4 14:37 新增
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.model).then((res) => {
            console.log(res)
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          }).then(() => {
            this.find()
          })
        }
      })
    },
    // HEINFO: 2020/7/4 14:37 编辑前处理： 显示表单弹框、清除验证
    handleUpdate(row) {
      this.model = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // HEINFO: 2020/7/4 14:41 编辑
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.model)
          update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }).then(() => {
            this.find()
          })
        }
      })
    },
    // HEINFO: 2020/7/4 15:09 删除
    del(roleId) {
      del({ roleId }).then(() => {
        this.$notify({
          title: '提示',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      }).then(() => {
        this.find()
      })
    },
    // HEINFO: 2020/7/9 14:03 批量删除
    multipleDel() {
      this.del(this.delIds)
    },
    selectionChange(selection) {
      selection.forEach((item) => {
        if (this.delIds === '') {
          this.delIds += item.roleId
        } else {
          this.delIds += ',' + item.roleId
        }
      })
    },
    // handleModifyStatus(row, status) {
    //   this.$message({
    //     message: '操作Success',
    //     type: 'success'
    //   })
    //   row.status = status
    // },

    // handleHeaderClick(column) {
    // console.log('handleHeaderClick')
    // console.log(column.multiOrder)
    // if (!column.multiOrder) {
    //   column.multiOrder = 'descending'
    // } else if (column.multiOrder === 'descending') {
    //   column.multiOrder = 'ascending'
    // } else if (column.multiOrder === 'ascending') {
    //   column.multiOrder = 'descending'
    // } else {
    //   column.multiOrder = ''
    // }
    // },
    // HEINFO: 2020/7/7 0:34 执行排序查询
    sortChange(data) {
      const { prop, order } = data
      const sortItem = { prop, order }
      // 返回非当前列的所有排序数据
      this.sortList = this.sortList.filter((item) => {
        // console.warn(item, prop, item.prop === prop)
        return item.prop !== prop
      })
      // sortItem.order有效时才加入排序
      if (sortItem.order) {
        this.sortList.push(sortItem)
      }
      this.listQuery.sort = ''
      this.sortList.forEach((item) => {
        if (this.listQuery.sort === '') {
          this.listQuery.sort += item.prop + '_' + item.order
        } else {
          this.listQuery.sort += ',' + item.prop + '_' + item.order
        }
      })
      this.find()
    },
    // HEINFO: 2020/7/7 0:33 保持自定义排序表头的样式，默认只能有一个自定义排序列样式有效
    handleHeaderCellClass({ column }) {
      if (column.sortable) {
        this.sortList.some((item) => {
          if (column.property === item.prop) {
            column.order = item.order
            return true
          }
        })
      }
    },
    handleLink() {
      // this.$router.push('/dashboard')
      this.$router.push('/platform/user')
    }
    // handleFetchPv(pv) {
    //   fetchPv(pv).then(response => {
    //     this.pvData = response.data.pvData
    //     this.dialogPvVisible = true
    //   })
    // },
    // handleDownload() {
    //   this.downloadLoading = true
    //     import('@/vendor/Export2Excel').then(excel => {
    //       const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
    //       const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
    //       const data = this.formatJson(filterVal)
    //       excel.export_json_to_excel({
    //         header: tHeader,
    //         data,
    //         filename: 'table-list'
    //       })
    //       this.downloadLoading = false
    //     })
    // },
    // formatJson(filterVal) {
    //   return this.list.map(v => filterVal.map(j => {
    //     if (j === 'timestamp') {
    //       return parseTime(v[j])
    //     } else {
    //       return v[j]
    //     }
    //   }))
    // },
    // getSortClass: function(key) {
    //   const sort = this.listQuery.sort
    //   return sort === `+${key}` ? 'ascending' : 'descending'
    // }
  }
}
</script>
